package com.front.listener;


import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListenerAdapter;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import com.front.common.StringUtils;
import com.front.constant.UserConstant;
import com.front.web.shiro.model.User;
import com.front.web.shiro.service.UserService;

public class FrontSessionListener extends SessionListenerAdapter{

    @Autowired
    private UserService userService;
    
    @Autowired
    private RedisSessionDAO redisSessionDao;
  
    
    
	@Override
	public void onExpiration(Session session) { 
		changeUserStatus(session);
	}
	 
	 
	@Override
	public void onStop(Session session) {
		  changeUserStatus(session);
	}
	
	
	/***
	 *  改变会员登录状态
	 * @param session
	 */
	private void changeUserStatus(Session session)
	{ 
	    Session s = redisSessionDao.readSession(session.getId()); 
        Object userName = session.getAttribute("org.apache.shiro.subject.support.DefaultSubjectContext_PRINCIPALS_SESSION_KEY");
        if (!StringUtils.isEmpty(userName))
        {
      	  String loginName =StringUtils.obj2String(userName);
      	  User user =userService.findByUserName(loginName);
            if(user!=null)
            {
          	  if(user.getIsOnline()==UserConstant.USER_ON_LINE)
          	  {
          		  userService.setUserLine(loginName, UserConstant.USER_OFF_LINE);
          	  }
            }
            else
            {
          	     userService.setUserLine(loginName, UserConstant.USER_OFF_LINE);
            }
        } 
	}
	
	
}
